package test2.java;

import java.util.Arrays;
import java.util.Iterator;

public class MyArrayList<T> implements Iterable<T> {
	
	private Object[] objs;
	
	int size;
	
	static int DEAFULT_SIZE = 10; 
	
	public MyArrayList() {
		objs = new Object[DEAFULT_SIZE];
	}
	
	public void add(Object obj) {
		size = size+1;
		int len = objs.length;
		if(size>len) {
			int newsize = len+len>>1;
			objs = Arrays.copyOf(objs, newsize);
		}
		objs[size-1] = obj;
	}
	
	public Object get(int index) {
		if(size==0||index<0||index>=size)	throw new ArrayIndexOutOfBoundsException();
		return objs[index];
	}
	
	public void del(Object obj) {
		int index = -1;
		for(int i=0;i<size;i++) {
			if(objs[i].equals(obj)) {
				index = i;
				break;
			}
		}
		System.out.println("找到要删除的元素，索引为"+index);
		if(index!=-1) {
			//0 1 2 3 4 5
			Object[] dest = new Object[size-1];
			System.arraycopy(objs, index+1, dest, index, size-index-1);
			objs = dest;
		}
	}

	@Override
	public Iterator<T> iterator() {
		return new Iterator<T>() {
			
			int cursor;

			@Override
			public boolean hasNext() {
				if(size==0||cursor>size-1)
					return false;
				else
					return true;
			}

			@SuppressWarnings("unchecked")
			@Override
			public T next() {
				return (T) objs[cursor++];
			}
			
		};
	}
	
}
